package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        // 1. 从 redis 中查询商铺类型缓存
        String key = CACHE_SHOPTYPE_KEY;
        List<String> list = stringRedisTemplate.opsForList().range(key, 0, -1);
        // 2. 判断是否命中
        if (list != null && !list.isEmpty()) {
            // 3. 如果命中，返回商铺类型信息
            List<ShopType> shopTypeList = list.stream().map(x -> JSONUtil.toBean(x, ShopType.class)).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        // 4. 如果没命中，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        // 5. 如果不存在，返回错误信息
        if (shopTypeList.isEmpty()) {
            return Result.fail("商铺分类不存在!");
        }
        // 6. 如果存在，将商铺类型信息写入 redis
        list = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, list);
        stringRedisTemplate.expire(key, CACHE_SHOPTYPE_TTL, TimeUnit.MINUTES);
        // 7. 返回商铺类型信息
        return Result.ok(shopTypeList);
    }
}
